<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2020 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://demo.thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\cms\controller;


use function PHPSTORM_META\type;
use think\admin\Controller;
use think\facade\Config;
use think\admin\service\AdminService;
use think\admin\extend\DataExtend;
use think\admin\service\MenuService;




/**
 * 单页信息管理
 * Class Singlepage
 * @package app\wechat\controller
 */
class Singlepage extends Controller
{

    /**
     * 当前操作数据库
     * @var string
     */
    protected $table = 'CmsArticles';
    protected $type = "info";

    /**
     * 单页信息管理
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $this->category_id = $this->request->get('category_id');
        $this->types = Config::get('app.category_type');
        $this->type_name = $this->types[$this->type];

        $this->title = $this->type_name."信息";
        $map = ['is_deleted' => '0',"type" =>$this->type];
        if($this->category_id)
            $map['category_id'] = $this->category_id;
        $query = $this->_query($this->table)->like('title')->where($map);
        $query->order('sort desc,id desc')->page();

    }

    /**
     * @return array  {"ccc":"aaa","222":"2222'}
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _get_category_dict(){
        $result = array();
        $category = $this->app->db->name('CmsCategory')->select()->toArray();
        foreach ($category as $value){
            $result[$value['id']] = $value['title'];
        }
        return $result;
    }

    /**
     * 数据列表处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _index_page_filter(&$data)
    {

        $this->category = $this->_get_category_dict();
        $this->clist = $this->app->db->name('CmsCategory')->select()->toArray();
        foreach ($this->clist as &$vo) {
            $vo['ids'] = join(',', DataExtend::getArrSubIds($this->clist, $vo['id'], $key = 'id', $pkey = 'parent_id'));
        }
        $this->clist = DataExtend::arr2table($this->clist, $key="id", $pkey="parent_id");

        foreach ($data as &$vo) {
            list($vo['list'], $vo['category']) = [[], []];
            foreach ($this->clist as $categorye) if ($categorye['id'] === $vo['id']) $vo['category'] = $categorye;
        }
    }


    /**
     * 表单数据处理
     * @param array $vo
     * @throws \ReflectionException
     */
    protected function _form_filter(&$vo)
    {

        if ($this->request->isGet()) {
            // 清理权限节点
            AdminService::instance()->clearCache();


            // 读取系统功能节点
            $this->nodes = MenuService::instance()->getList();
            // 选择自己的上级菜单
            if (empty($vo['category_id']) && $this->request->get('category_id', '0'))
                $vo['category_id'] = $this->request->get('category_id', '0');
            // 列出可选上级菜单
            $menus = $this->app->db->name("CmsCategory")->where(['status' => '1'])->order('sort desc,id asc')->column('id,parent_id,title,type', 'id');

            $this->menus = DataExtend::arr2table(array_merge($menus, [['id' => '0', 'parent_id' => '-1', 'title' => '顶级分类']]),$key="id",$pkey="parent_id");
            if (isset($vo['id'])) foreach ($this->menus as $key => $menu) if ($menu['id'] === $vo['id']) $vo = $menu;
            foreach ($this->menus as $key => &$menu) {
                if ($menu['spt'] >= 3) unset($this->menus[$key]);
                if (isset($vo['spt']) && $vo['spt'] <= $menu['spt']) unset($this->menus[$key]);
            }
            $this->types = Config::get('app.category_type');
        }

    }

    /**
     * 添加单页信息
     * @auth true
     * @throws \think\db\exception\DbException
     */
    public function add()
    {
        $this->category_id= $this->request->get('category_id');
        $map = array();
        $this->clist = $this->app->db->name('CmsCategory')->where($map)->select()->toArray();
        foreach ($this->clist as &$vo) {
            $vo['ids'] = join(',', DataExtend::getArrSubIds($this->clist, $vo['id'], $key = 'id', $pkey = 'parent_id'));
        }
        $this->clist = DataExtend::arr2table($this->clist, $key="id", $pkey="parent_id");
        for ($i=0;$i<count($this->clist);$i++) {
            //var_dump($this->type);
            if($this->clist[$i]['type']!=$this->type){
                // var_dump($this->clist[$i]);
                $this->clist[$i]['disable'] = true;
                // $arr[$this->clist[$i]['disable']] = true;
            }else{
                // $arr[$this->clist[$i]['disable']] = false;
                $this->clist[$i]['disable'] = false;
            }
        }

        if ($this->request->isGet()) {
            $this->_applyFormToken();
            $this->_form($this->table, 'form');
        } else {

            $update = $this->request->post('data', []);
            $update[ 'create_by']   = AdminService::instance()->getUserId();
            $update[ 'type' ]= $this->type;
            $update[ 'create_at'] = time();
            if (empty($update['digest'])) {
                $update['digest'] = mb_substr(strip_tags(str_replace(["\s", '　'], '', $update['content'])), 0, 120);
            }
            if ($this->app->db->name($this->table)->insert($update) !== false) {
                $this->success('添加成功！','javascript:history.back()');
            } else {
                $this->error('添加失败，请稍候再试！');
            }
        }
    }

    /**
     * 编辑单页信息
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        $this->type= $this->request->get('type');
        $this->category_id= $this->request->get('category_id');
        //$map = ["type" =>$this->type];
        $map = array();
        $this->clist = $this->app->db->name('CmsCategory')->where($map)->select()->toArray();
        foreach ( $this->clist as &$vo) {
            $vo['ids'] = join(',', DataExtend::getArrSubIds( $this->clist, $vo['id'], $key = 'id', $pkey = 'parent_id'));
        }
        $this->clist = DataExtend::arr2table( $this->clist, $key="id", $pkey="parent_id");
        for ($i=0;$i<count($this->clist);$i++) {
            //var_dump($this->type);
            if($this->clist[$i]['type']!=$this->type){
               // var_dump($this->clist[$i]);
                $this->clist[$i]['disable'] = true;
               // $arr[$this->clist[$i]['disable']] = true;
            }else{
               // $arr[$this->clist[$i]['disable']] = false;
                $this->clist[$i]['disable'] = false;
            }
        }
             //var_dump($this->clist);
        $this->id = $this->request->get('id');
        $map = array("id" => $this->id);
        if (empty($this->id)) $this->error('参数错误，请稍候再试！');
        if ($this->request->isGet()) {
            if ($this->request->get('output') === 'json') {
                $this->success('获取数据成功！', $this->app->db->name($this->table)->where($map)->find());
            } else {
                $this->title = '编辑图文';
                $this->_applyFormToken();
                $this->_form($this->table, 'form');
            }
        }else{
            $data = $this->request->post('data', []);
            if (empty($data['digest'])) {
                $data['digest'] = mb_substr(strip_tags(str_replace(["\s", '　'], '', $data['content'])), 0, 120);
            }
            $data['update_at'] = time();
            if ($this->app->db->name($this->table)->where($map)->update($data) !== false) {
                $this->success('图文更新成功！', 'javascript:history.back()');
            } else {
                $this->error('图文更新失败，请稍候再试！');
            }
        }

    }

    /**
     * 删除单页信息
     * auth true
     * @throws \think\db\exception\DbException
     */
    public function remove()
    {
        $this->_delete($this->table);
    }

}
